/*eslint-disable */
import utils from "@common/utils/utils";
import { message } from '@common/assets/js/resetMessage';
import common from "@common/api/common";
import sysResourceApi from "@common/api/system/sysResourceApi";
import baseRelatedPartyApi from "@common/api/base/baseRelatedPartyApi";
import { eachPermission } from '../utils/permission';
import upload from "@common/utils/upload";
import apiConstants from "../api/constants";

// 全局
export default {
    state: {
        vuexName: 'tsdVuex',
        storageName: 'tsd_current',
        accountSetSid: 'tsd_accountSetSid',
        rememberUser: 'rememberUser',
        tokenName: 'tsd_token',
        systemId: [
            'master',
            'jxc'
        ],
        globalJson: {},
        userInfo: {},
        accessToken: {},
        refreshToken: {},
        projectHistory: {},
        permission: {},
        menus: [],
        clientList: [],
        global_setting: {},
        table_setting: [],
        application: '',
        user_setting: {},
        version_map: null,
    },
    mutations: {
        setState(state, { propName, value }) {
            state[propName] = value;
        },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
            state.accessToken = userInfo.accessToken;
            state.refreshToken = userInfo.refreshToken;
        },
        setMenus(state, menus) {
            state.menus = menus;
        },
        setPermission(state, permission) {
            state.permission = permission;
        },
        setGlobalJson(state, globalJson) {
            state.globalJson = globalJson;
        },
        setGlobalSetting(state, globalSetting) {
            state.global_setting = globalSetting;
        },
        setTableSetting(state, tableSetting) {
            state.table_setting = tableSetting;
        },
        setProjectHistory(state, projectHistory) {
            state.projectHistory = projectHistory;
        },
        setApplication(state, application) {
            state.application = application;
        },
        setUserSetting(state, userSetting) {
            state.user_setting = userSetting;
        },
        setVersionMap(state, versionMap) {
            state.version_map = versionMap;
        },
    },
    actions: {
        initGlobalSetting({ commit }) {
            return common.requestData(apiConstants.API_GetSysSetting3rd, {
                account_set_sid: utils.getAccountSetSid(),
                code: 'global_setting',
            }).then(result => {
                let resData = result.data || {};
                let data = {};
                if (utils.isNotEmpty(resData.json_object)) {
                    data = $.extend({}, resData.json_object);
                }
                data.id = resData.id;
                data.sid = resData.sid;
                if (utils.isEmpty(data.related_party_display)) {
                    data.related_party_display = 'name';
                }
                if (utils.isEmpty(data.enable_data_auth)) {
                    data.enable_data_auth = 0;
                }
                if (utils.isEmpty(data.enable_data_auth_field)) {
                    data.enable_data_auth_field = 0;
                }
                commit('setGlobalSetting', data);
                return data;
            }).catch(err => {
                message.error(err.message);
                return Promise.reject(err);
            })
        },
        initUserSetting({ commit }, user) {
            return common.requestData(apiConstants.API_GetSysSettingByCodeOwnerId, {
                account_set_sid: utils.getAccountSetSid(),
                code: user,
            }).then(result => {
                let resData = result.data || {};
                commit('setUserSetting', {
                    id: resData.id,
                    sid: resData.sid,
                    code: resData.code,
                    json: resData.json,
                    json_object: resData.json_object,
                });
                return resData;
            }).catch(err => {
                message.error(err.message);
                return Promise.reject(err);
            })
        },
        initMenu({ commit, state }) {
            return new Promise(resolve => {
                let queryData = {};
                queryData.parent_code = state.systemId;
                sysResourceApi.findResourceTree4User(queryData, result => {
                    let permissionArr = eachPermission(result.data || []);
                    commit('setPermission', permissionArr);
                    window.userMenuData = result.data || [];
                    resolve();
                }, error => {
                    message.error(error.message);
                });
            });
        },
        initClientList({ commit, state }) {
            return new Promise(resolve => {
                let clientList = []
                sysClientsApi.findSysClients({ nopage: '1' }, result => {
                    if (result.data) {
                        clientList = result.data.map(item => {
                            return {
                                sid: item.sid,
                                code: item.code,
                                name: item.name,
                                value: item.sid,
                                label: item.code,
                            }
                        })
                    }
                    commit('setState', { propName: 'clientList', value: clientList });
                    resolve(clientList);
                })
            });
        },
        fetchData(store, { url, data = {}, error = true, addLog = true, headers={} }) {
            const fun = () => {};
            return common.requestData(url, data, fun, fun, fun, addLog, headers).then(result => {
                if (result.code !== 0) {
                    return Promise.reject(result);
                }
                return result;
            }).catch(err => {
                if (error) {
                    message.error(err.message);
                }
                return Promise.reject(err);
            })
        },
        autoAddErrorLog({ state, dispatch }, result) {
            if (result.trace == undefined){
                return
            }
            let path = window.location.hash.replace('#', '');
            let filter = (state.menus || []).filter(item => utils.isNotEmpty(item.target_url) && item.target_url !== '/' && path.indexOf(item.target_url) === 0);
            if (utils.isNotEmptyList(filter)) {
                let list = [];
                if (utils.isNotEmpty(filter[0].parent_name)) {
                    list = filter[0].parent_name.split(',');
                }
                list.push(filter[0].name);
                let data = {
                    path,
                    menu: filter[0],
                    name: list.join(' > '),
                    error: result.message,
                    trace: result.trace,
                    date: utils.formatDate(new Date(), 'HH:mm:ss'),
                };
                dispatch('errorLog/addErrorLog', data);
            }
        },
        uploadBase64(store, data) {
            return upload.uploadBase64Slice(data);
        },
        initTableSetting({ commit, dispatch }, query = {}) {
            return dispatch('fetchData', {
                url: apiConstants.API_QueryCommonTableSetting4User,
                data: {
                    hideLoading: true,
                    ...query,
                },
            }).then(result => {
                let resData = result.data || [];
                commit('setTableSetting', resData);
                return resData;
            }).catch(() => {
            })
        },
        saveTableSetting({ state, commit, dispatch }, { table, tableOptions, route, reset = false }) {
            let tableSetting = (state.table_setting || []).map(item => $.extend({}, item));
            let columns = (table.tableFullColumn || []).map(item => {
                return {
                    prop: item.field || item.property,
                    label: item.title,
                    visible: item.visible,
                    width: item.width,
                    minWidth: item.minWidth,
                    resizeWidth: item.resizeWidth,
                    renderWidth: item.renderWidth,
                };
            });
            let pagination = {
                reset,
            };
            if (tableOptions.pagination) {
                pagination.pageSize = tableOptions.pagination.pageSize;
            }
            let subData = {
                router_path: route.fullPath,
                type: tableOptions.ref,
                columns_json: JSON.stringify(columns),
                page_json: JSON.stringify(pagination),
            };
            let filter = tableSetting.filter(item => item.router_path === subData.router_path && item.type === subData.type);
            if (subData.router_path === 'application') {
                filter = tableSetting.filter(item => item.router_path === subData.router_path);
            }
            if (utils.isNotEmptyList(filter)) {
                subData.id = filter[0].id;
                subData.sid = filter[0].sid;
                if (subData.router_path === 'application') {
                    if (filter[0].type === subData.type) {
                        return undefined;
                    }
                }
            }
            subData.hideLoading = true;
            return dispatch('fetchData', {
                url: apiConstants.API_SaveCommonTableSetting,
                data: subData,
            }).then(result => {
                let resData = result.data || {};
                if (utils.isNotEmptyList(filter)) {
                    tableSetting = tableSetting.map(item => {
                        let obj = $.extend({}, item);
                        if (obj.sid === subData.sid) {
                            obj = $.extend({}, obj, subData);
                        }
                        return obj;
                    });
                } else {
                    tableSetting.push(resData);
                }
                commit('setTableSetting', tableSetting);
                return resData;
            }).catch(() => {
                return undefined;
            })
        },
        initVersionMap({commit}) {
            return new Promise(resolve => {
                common.requestData(apiConstants.Anon_QueryVersionMap, {
                    hideLoading: true,
                }).then(result => {
                    let resData = result.data || {};
                    commit('setVersionMap', resData);
                    resolve(resData);
                }).catch(err => {
                    resolve();
                });
            });
        },
    },
    getters: {
        getSidByPath: (state) => (path) => {
            let filters = state.menus.filter(item => {
                return item.target_url && item.target_url.trim() === path;
            });
            return filters.length > 0 ? filters[0].sid : '';
        },
        getMenuByPath: (state) => (path) => {
            let filters = state.menus.filter(item => {
                return item.target_url && item.target_url.trim() === path;
            });
            return filters.length > 0 ? filters[0] : {};
        },
        getModuleData: (state) => (module, fieldName) => {
            let data = state[module];
            if (utils.isNotEmpty(fieldName)) {
                return data[fieldName];
            }
            return data;
        },
    }
}
